package com.chuangke.mds.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chuangke.common.db.page.CkPageQuery;
import com.chuangke.common.idgen.IdManager;
import com.chuangke.common.trans.annotation.TransResult;
import com.chuangke.mds.dao.MaterialAttributeConfDao;
import com.chuangke.mds.entity.MaterialAttributeConf;
import com.chuangke.mds.service.MaterialAttributeConfService;

import cn.hutool.core.util.StrUtil;

@Service
@Transactional(rollbackFor = Throwable.class)
public class MaterialAttributeConfServiceImpl implements MaterialAttributeConfService {

	@Autowired
	private MaterialAttributeConfDao confDao ;
	
	@Override
	public String save(MaterialAttributeConf model) {
		return saveOrUpdate(model);
	}
	
	@Override
	public void update(MaterialAttributeConf model) {
		saveOrUpdate(model);
	}

	@Override
	public String saveOrUpdate(MaterialAttributeConf model) {
		if (StrUtil.isBlank(model.getId())) {
			doSave(model) ;
		}else{
			doUpdate(model) ;
		}
		return model.getId() ;
	}
	
	private void doSave(MaterialAttributeConf model) {
		model.setId(IdManager.nextId());
		confDao.save(model) ;
	}

	
	private void doUpdate(MaterialAttributeConf model) {
		confDao.updateById(model) ;
	}

	@Override
	public void delete(List<String> billIds) {
		QueryWrapper<MaterialAttributeConf> qw = new QueryWrapper<MaterialAttributeConf>() ;
		qw.lambda().in(MaterialAttributeConf::getId, billIds) ;

		confDao.remove(new QueryWrapper<MaterialAttributeConf>().lambda().in(MaterialAttributeConf::getId, billIds));

	}

	@Override
	@TransResult
	public MaterialAttributeConf load(String billId) {
		MaterialAttributeConf conf = confDao.getOne(new QueryWrapper<MaterialAttributeConf>().lambda().eq(MaterialAttributeConf::getId, billId)) ;
		return conf;
	}

	@Override
	@TransResult
	public IPage<MaterialAttributeConf> page(CkPageQuery page) {
		QueryWrapper<MaterialAttributeConf> qw = new QueryWrapper<>();
		if(!StringUtils.isEmpty(page.getAsString("name"))) {
			qw.lambda().like(MaterialAttributeConf::getName, page.getAsString("name")).or().like(MaterialAttributeConf::getType, page.getAsString("name")) ;
		}
		
		qw.lambda().orderByDesc(MaterialAttributeConf::getCreatedAt) ;

		return confDao.page(page.getPage(),qw);
	}


}
